/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.dream.modules.system.rest;

import com.dream.modules.system.service.UserService;
import com.dream.modules.system.service.dto.JobSmallDto;
import com.dream.modules.system.service.dto.UserDto;
import com.dream.service.TaskWorkService;
import com.dream.service.dto.TaskGatherDto;
import com.dream.service.dto.TaskWorkQueryCriteria;
import com.dream.utils.DateUtil;
import com.dream.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import com.dream.annotation.Log;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
* @website https://el-admin.vip
* @author syl
* @date 2020-07-06
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "工时管理：工时统计")
@RequestMapping("/api/gather")
public class TaskWorkGatherController {

    private final TaskWorkService taskWorkService;

    private final UserService userService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('gather:list')")
    public void download(HttpServletResponse response, TaskWorkQueryCriteria criteria) throws IOException {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if(currentUserId !=1){
            UserDto user = userService.findById(currentUserId);
            Set<JobSmallDto> jobs = user.getJobs();
            Iterator<JobSmallDto> iterator = jobs.iterator();
            while (iterator.hasNext()){
                if("项目经理".equals(iterator.next().getName())){
                    criteria.setLeaderId(currentUserId.intValue());
                }
            }
            if(null == criteria.getLeaderId()){
                criteria.setTaskUserId(currentUserId.intValue());
            }
            if(null == criteria.getStartDate()){
                LocalDateTime start = LocalDateTime.now().plusDays(-30);
                criteria.setStartDate(DateUtil.localDateTimeFormatyMd(start));
            }
            if(null == criteria.getEndDate()){
                LocalDateTime end = LocalDateTime.now().plusDays(-1);
                criteria.setEndDate(DateUtil.localDateTimeFormatyMd(end));
            }
        }
        taskWorkService.downloadGather(criteria,response);
    }

    @GetMapping
    @Log("查询工时统计列表")
    @ApiOperation("查询工时")
    @PreAuthorize("@el.check('gather:list')")
    public ResponseEntity<Object> query(TaskWorkQueryCriteria criteria, Pageable pageable){
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if(currentUserId !=1){
            UserDto user = userService.findById(currentUserId);
            Set<JobSmallDto> jobs = user.getJobs();
            Iterator<JobSmallDto> iterator = jobs.iterator();
            while (iterator.hasNext()){
                if("项目经理".equals(iterator.next().getName())){
                    criteria.setLeaderId(currentUserId.intValue());
                }
            }
            if(null == criteria.getLeaderId()){
                criteria.setTaskUserId(currentUserId.intValue());
            }
            if(null == criteria.getStartDate()){
                LocalDateTime start = LocalDateTime.now().plusDays(-30);
                criteria.setStartDate(DateUtil.localDateTimeFormatyMd(start));
            }
            if(null == criteria.getEndDate()){
                LocalDateTime end = LocalDateTime.now().plusDays(-1);
                criteria.setEndDate(DateUtil.localDateTimeFormatyMd(end));
            }
        }
        checkParam(criteria);
        List<TaskGatherDto> taskGatherDtos = taskWorkService.gather(criteria);
        Map<String, Object> result = null;
        if(!ObjectUtils.isEmpty(taskGatherDtos)) {
            result = new HashMap<String, Object>(taskGatherDtos.size());
            result.put("content", taskGatherDtos);
            result.put("totalElements",taskGatherDtos.size());
        }else{
            result = new HashMap<>();
            result.put("content", new ArrayList<>());
            result.put("totalElements",0);
        }
        return new ResponseEntity<>(result,HttpStatus.OK);
    }

    /**
     * 参数判断是否填写开始日期和结束日期
     *  日期默认是1977年到2999年，表示查全部
     *  项目名称默认''查全部
     * @param criteria
     */
    private void checkParam(TaskWorkQueryCriteria criteria) {
        // 简单粗暴的方法判断
        if(criteria.getStartDate()==null){
            criteria.setStartDate("1977-01-01");
        }
        if(criteria.getEndDate()==null){
            criteria.setEndDate("2999-12-31");
        }
        if(criteria.getBlurry()==null){
            criteria.setBlurry("");
        }
    }


}